package com.hexb.smh.config.shiro;

import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.util.ThreadContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.apache.shiro.mgt.SecurityManager;
import org.springframework.web.filter.DelegatingFilterProxy;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author : hexb
 */
@Configuration
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class SmhShiroConfig {

    @NonNull
    final private SmhAuthorizingRealm smhAuthorizingRealm;

    @NonNull
    final private EhCacheManager ehCacheManager;

    @Bean
    public SecurityManager smhCreateSecurityManager() {
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setCacheManager(ehCacheManager);
        securityManager.setRealm(smhAuthorizingRealm);
        securityManager.setSessionManager(sessionManager());
        return securityManager;
    }

    @Bean(name = "'shiroFilter'")
    public ShiroFilterFactoryBean smhShiroFilterBean() {
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        bean.setSecurityManager(smhCreateSecurityManager());
        Map<String, String> filterChainDefinitionMap = new LinkedHashMap<>();
        filterChainDefinitionMap.put("/", "anon");
        filterChainDefinitionMap.put("/static/**", "anon");
        filterChainDefinitionMap.put("/avatar/**", "anon");
        bean.setFilterChainDefinitionMap(filterChainDefinitionMap);
        return bean;
    }

    //
    @Bean
    public SessionManager sessionManager() {
        return new AdminWebSessionManager();
    }

}
